package org.groovyflow.validation

import org.groovyflow.util.Money
import org.groovyflow.util.Rule
import java.text.SimpleDateFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

interface Validations{

static def REQUIRED_PRED = {prop, args ->
      return (prop == null || prop.trim().length() == 0)              
}
static def REQUIRED_ACTION =  {prop, args ->
	return "cannot be blank"
}

static def REQUIRED = new Rule(pred: REQUIRED_PRED, action: REQUIRED_ACTION)

static def INTEGER = {prop, args ->
            try{
                 Integer.parseInt(prop)
            }catch(Exception ex){
                return "'" + prop + "' is not an integer"
            }
}
static def POSITIVE_INTEGER = {prop, args ->
    def anInt =Integer.parseInt(prop)
    if(anInt <= 0)    
         return "'" + prop + "' is not a positive integer"
}

//Also handles check that incomming variable is an integer
static def NONNEGATIVE_INTEGER = {prop, args ->
	int x = 0
	try{
	    x = Integer.parseInt(prop)
	}catch(Exception ex){
	   return "'" + prop + "' is not an integer"
	}
	if(x < 0)
		 return "'" + prop + "' is a negative integer"
}

static def MONEY_PRED = {prop, args ->
    try{
        new Money(prop)
    }catch(Exception){
        return true;
    }
    return false;
}

static def MONEY_ACTION =  {prop, args ->
     return "'" + prop + "' is not a valid monetary amount"
}

def MONEY_RULE = new Rule(pred: MONEY_PRED, action: MONEY_ACTION)


static Pattern MM_DD_YYYY_REGEXP  = Pattern.compile("\\d\\d[/]\\d\\d[/]\\d\\d\\d\\d");

static def DATE_MMDDYY = {prop, args ->
    try{
        SimpleDateFormat fmt = new SimpleDateFormat("MM/dd/yyyy")
        fmt.setLenient(false)
       fmt.parse(prop)
    }catch(Exception ex){
        Matcher m = MM_DD_YYYY_REGEXP.matcher(prop);
        if(!m.matches()){
            return "'" + prop + "' is not in mm/dd/yyyy format."
        }else
            return "'" + prop + "' is not a valid date."
    }
}    



}